package com.ksd.dao.impl;

import com.ksd.dao.IUserDAO;
import com.ksd.pojo.User;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import java.util.List;

public class UserDAO implements IUserDAO {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public boolean isValid(final String username, final String password) {
        List list = sessionFactory.getCurrentSession().createCriteria(User.class).add(
                Restrictions.eq("username", username)).add(
                Restrictions.eq("password", password)).list();
        return list.size() > 0;
    }

    public boolean isExist(final String username) {
        List list = sessionFactory.getCurrentSession().createCriteria(User.class).add(
                Restrictions.eq("username", username)).list();
        return list.size() > 0;
    }

    public void insertUser(User user) {
        sessionFactory.getCurrentSession().saveOrUpdate(user);
    }

    public User getUserByName(String username) {
        return (User) sessionFactory.getCurrentSession().createCriteria(User.class).add(
                Restrictions.eq("username", username)).list().get(0);
    }

    public User getUser(String userId) {
        return (User) sessionFactory.getCurrentSession().get(User.class,
                new Integer(userId));
    }

    public List getUsers() {
        return sessionFactory.getCurrentSession().createQuery("from User").list();
    }

    public void deleteUser(String userid) {
        Object p = sessionFactory.getCurrentSession().load(User.class, new Integer(userid));
        sessionFactory.getCurrentSession().delete(p);
    }
}
